package cn.tedu.charging.user.controller;

import cn.tedu.charging.user.service.IChargingUserInfoService;
import cn.tedu.charging.user.utils.AlipayUtil;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author mumuwei
 * @date 0004
 */
@RestController
@CrossOrigin
@Slf4j
public class AlipayController {

    private AlipayUtil alipayUtil;

    @Autowired
    IChargingUserInfoService chargingUserInfoService;

    @Autowired
    public void setAlipayUtil(AlipayUtil alipayUtil) {
        this.alipayUtil = alipayUtil;
    }


    /**
     * 调用支付宝支付
     * @param userId 用户编号
     * @param amount 金额
     * @return
     */
    @GetMapping("/create")
    public String create(String userId, String amount) {

        //支付订单号包含用户编号_随机数
        String billId = userId + "_" + UUID.randomUUID().toString();
        //用户最多只能充值50元
        int iAmount = Integer.parseInt(amount);
        if (iAmount > 500) {
            amount = "500";
        }
        String pay = alipayUtil.pay(billId, amount, "智慧充电充值订单");
        return pay;
    }

    /**
     * 这个接口由支付宝服务器调用
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {

        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            //调用支付框架中的方法判断收到的数据是不是支付服务器发送的
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content,
                    sign, alipayUtil.publicKey, "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
            // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家支付宝ID: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));


                // 更新数据库
                String outTradeNo = params.get("out_trade_no");
                String userIdStr = outTradeNo.substring(0, outTradeNo.indexOf("_"));
                Integer userId = Integer.parseInt(userIdStr);

                String amountStr = params.get("total_amount");
                BigDecimal amount = new BigDecimal(amountStr);
                //chargingUserInfoService.recharge(userId, amount);
                return "success";
            } else {
                return "fail";
            }
        }
        return "fail";
    }

}
